package operator;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Created by huangxiaoli on 2019/11/27 13:46
 */
public class GroupByKey {

    public static void main(String[] args) {
        SparkConf conf = new SparkConf()
                .setAppName("groupByKey")
                .setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(conf);
        List<Tuple2<String, Integer>> scoreList = Arrays.asList(
                new Tuple2<String, Integer>("class1", 80),
                new Tuple2<String, Integer>("class2", 90),
                new Tuple2<String, Integer>("class1", 97),
                new Tuple2<String, Integer>("class2", 89));

        JavaPairRDD<String, Integer> scores = sc.parallelizePairs(scoreList);
        //针对scoresRDD，执行groupByKey算子，对每个班级的成绩进行分组
        //相当于是，一个key join上的所有value，都放到一个Iterable里面去了
        JavaPairRDD<String, Iterable<Integer>> groupedScores = scores.groupByKey();
        groupedScores.foreach(new VoidFunction<Tuple2<String,Iterable<Integer>>>() {

            @Override
            public void call(Tuple2<String, Iterable<Integer>> t)
                    throws Exception {
                System.out.println("class:" + t._1);
                Iterator<Integer> ite = t._2.iterator();
                while(ite.hasNext()) {
                    System.out.println(ite.next());
                }
            }
        });
    }

}
